<?php
/**
 * Created by CuiLiwu.
 * User: CuiLiwu
 * Date: 2018/4/18
 * Time: 14:57
 */

namespace App\Http\Controllers\Web\Buyer;
use App\ConstDir\ErrorConst;
use Illuminate\Http\Request;
use App\Repository\Repositories\Interfaces\UserCollectionRepository;
use App\Http\Controllers\Web\BaseController;

/**
 * 我的收藏 控制器
 */
class UserCollectionController extends BaseController
{

    /**
     * @var UserCollectionRepository
     */
    protected $collection_repo;

    protected $user_id;

    public function __construct(UserCollectionRepository $collection_repo,Request $request)
    {
        parent::__construct();

        $this->user_id = array_get($this->user, 'id');

        $this->collection_repo = $collection_repo;
        $this->request = $request;
        // 用户只能操作自身所属数据
        $this->collection_repo->scopeQuery(function ($query) {
            return $query->with(['sku','product','shop'])->where(['user_id'=>$this->user_id]);
        });
    }

    public function index(Request $request)
    {
//        $collection = $this->collection_repo->all();

        $collection = $this->collection_repo->paginate($this->perPage);
        return $this->success(ErrorConst::SUCCESS_CODE, $collection, true);
//        return $this->success(ErrorConst::SUCCESS_CODE, $collection['data'], true);
    }

    public function show($id)
    {
        $collection = $this->collection_repo->find($id);
        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $collection['data']);
    }

    /**
     * 创建
     * @param Request $request
     * @return \Illuminate\Support\Collection
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'shop_id'   => 'integer',
            'product_id'=> 'integer|exists:products,id',
            'sku_id'    => 'integer|exists:product_skus,id',
            'type'      => 'integer|in:1,2',// 1 是商品收藏 2 是店铺收藏
            'is_invalid'=> 'integer|in:1,2',
        ],[
            'shop_id'   => '店铺id必须为数字类型',
            'product_id'=> 'product_id必须为数字|商品id 不合法',
            'sku_id'    => 'sku_id 必须为数字|sku_id 不合法',
            'type'      => 'type必须为数字|type必须为1或2',
            'is_invalid'=> 'integer|is_invalid必须为1或2',
        ]);
        $data = $request->all();
        $data['user_id'] = $this->user_id;
        if ($data['type']==1){// 商品收藏
            $where = ['product_id' =>$data['product_id'],'sku_id'=>$data['sku_id'],'user_id'=>$this->user_id,'type'=>1];
        }else{// 店铺收藏
            if (isset($data['product_id'])){
                unset($data['product_id']);
            }
            $where = ['shop_id'=>$data['shop_id'],'user_id'=>$this->user_id,'type'=>2];
        }

        $ret = $this->collection_repo->updateOrCreate($where, $data);

        return $this->noDataReturn($ret ? true : false);
    }

    /**
     * 更新
     * @param Request $request
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'shop_id'   => 'integer',
            'user_id'   => 'required|integer',
            'product_id'=> 'integer',
            'sku_id'    => 'integer',
            'type'      => 'integer|in:1,2',
            'is_invalid'=> 'integer|in:1,2',
        ],[
            'shop_id'   => '店铺id必须为数字类型',
            'user_id'   => '无用户id|用户id',
            'product_id'=> 'product_id必须为数字',
            'sku_id'    => 'sku_id 必须为数字',
            'type'      => 'type必须为数字|type必须为1或2',
            'is_invalid'=> 'integer|is_invalid必须为1或2',
        ]);
        $data = $request->all(['area_code', 'address', 'receiver', 'phone']);

        $ret = $this->collection_repo->update($data, $id);

        return $this->noDataReturn($ret ? true : false);
    }

    public function updateSetDefault($id)
    {
        $ret = $this->collection_repo->setDefault($id);
        return $this->noDataReturn($ret ? true : false);
    }

    public function delete($id)
    {
        $ret = $this->collection_repo->delete($id);
        return $this->noDataReturn($ret ? true : false);
    }
    public function multiDelete(Request $request)
    {
        $data = $request->only('ids');
        if (count($data['ids'])>0){
            $foreach = array_filter($data['ids']);
            foreach ($foreach as $key=>$value){
                $ret = $this->collection_repo->delete($value);
            }
        }else{
            $ret = false;
        }

        return $this->noDataReturn($ret ? true : false);
    }
    /**
     * 根据商品 sku_id 检测是否已关注店铺，是否已关注商品
     * */
    public function checkCollection($sku_id,$shop_id){
        $ret = $this->collection_repo->checkCollection($sku_id,$shop_id,$this->user_id);

        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $ret);
    }
    /**
     * 根据商品 sku_ids 检测是否已关注店铺，是否已关注商品
     * */
    public function checkMultiCollection(){
        $sku_ids = $this->request->get('sku_ids');
        $ret = $this->collection_repo->checkMultiCollection($sku_ids,$this->user_id);

        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $ret);
    }
    
    public function log($data,$filename){
        if(empty($filename)){
            $log_filename=$_SERVER['DOCUMENT_ROOT'].'/ecclub.php';
        }
        else{
            $log_filename=$_SERVER['DOCUMENT_ROOT'].'/'.$filename.'.php';
        }
        // 如果文件夹不存在则创建文件夹
        is_dir(dirname($log_filename)) || mkdir(dirname($log_filename),0777,true);
        // 日志大小
        $max_size=10485760;
        // 判断文件大小做自动删除动作
        if(file_exists($log_filename) && abs(filesize($log_filename))>$max_size){
            // 删除文件
            unlink($log_filename);
        }else{
            // 写日志(第三个参数是系统函数，可以连续写文件不覆盖)
            file_put_contents($log_filename, date("Y-m-d H:i:s",time()+8*60*60)." ".$data."\n", FILE_APPEND);
        }
    }
}